package net.neptech.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import net.neptech.api.SystemApi;
import net.neptech.dto.sys.StaffDTO;
import net.neptech.mapper.InstanceUserCopyMapper;
import net.neptech.model.workflow.InstanceRecord;
import net.neptech.model.workflow.InstanceUserCopy;
import net.neptech.service.InstanceRecordService;
import net.neptech.service.InstanceUserCopyService;
import net.neptech.service.WorkflowService;
import net.neptech.utils.SecurityUtils;
import net.neptech.model.vo.DataQueryVO;
import net.neptech.model.vo.InstanceCopyVo;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author Saya
 * @Date 2025/8/22 11:17
 * @Description TODO
 **/
@Service
@RequiredArgsConstructor
public class InstanceUserCopyServiceImpl extends ServiceImpl<InstanceUserCopyMapper, InstanceUserCopy> implements InstanceUserCopyService {
    private final InstanceRecordService instanceRecordService;
    private final WorkflowService workflowService;
    private final SystemApi systemApi;

    /**
     * 查询抄送给我的(根据实例id去重)
     */
    @Override
    public Page<InstanceCopyVo> queryMineCCProcessInstance(DataQueryVO pageDto) {
        List<String> flowIdList = pageDto.getFlowIdList();
        if (CollUtil.isNotEmpty(flowIdList)) {
            flowIdList = workflowService.getAllRelatedFlowId(flowIdList);
        }
        Long userId = SecurityUtils.getUserId();
        Page<InstanceUserCopy> page = this.lambdaQuery().eq(InstanceUserCopy::getUserId, userId).in(CollUtil.isNotEmpty(flowIdList), InstanceUserCopy::getFlowId, flowIdList).orderByDesc(InstanceUserCopy::getCreateTime).page(new Page<>(pageDto.getPageNum(), pageDto.getPageSize()));
        List<InstanceUserCopy> records = page.getRecords();
        List<InstanceCopyVo> processCopyVoList = BeanUtil.copyToList(records, InstanceCopyVo.class);
        if (CollUtil.isNotEmpty(records)) {
            //发起人
            Set<String> startUserIdSet = records.stream().map(InstanceUserCopy::getStartUserId).collect(Collectors.toSet());
            List<StaffDTO> startUserList = new ArrayList<>();
            for (String s : startUserIdSet) {
                StaffDTO user = systemApi.getStaffByUserId(s).getData();
                startUserList.add(user);
            }
            Set<String> processInstanceIdSet = records.stream().map(InstanceUserCopy::getProcessInstanceId).collect(Collectors.toSet());
            //流程实例记录
            List<InstanceRecord> instanceRecord = instanceRecordService.lambdaQuery().in(InstanceRecord::getProcessInstanceId, processInstanceIdSet).list();
            for (InstanceCopyVo record : processCopyVoList) {
                InstanceRecord processInstanceRecord = instanceRecord.stream().filter(w -> StrUtil.equals(w.getProcessInstanceId(), record.getProcessInstanceId())).findFirst().orElse(null);
                startUserList.stream().filter(w -> w.getUserId().equals(record.getStartUserId())).findAny().ifPresent(startUser -> record.setStartUserName(startUser.getStaffName()));
                record.setStartTime(processInstanceRecord.getCreateTime());
                record.setProcessInstanceStatus(processInstanceRecord.getStatus());
                record.setProcessInstanceResult(processInstanceRecord.getResult());
            }
        }
        Page<InstanceCopyVo> res = new Page<>();
        BeanUtil.copyProperties(page, res);
        res.setRecords(processCopyVoList);
        return res;
    }

    /**
     * 清理数据
     */
    @Override
    public void clearProcess(List<String> flowIdList) {
        this.lambdaUpdate().in(InstanceUserCopy::getFlowId, flowIdList).remove();

    }
}
